<!DOCTYPE html>
<html>
  <head><meta name="generator" content="Hexo 3.9.0">
<meta name="google-site-verification" content="fQ_tfBgNjE9NQcpKnGAkWapHoKuimF5lVuNuqpPXar0">
    <meta charset="utf-8">
    
    <title>BASE64编码原理学习笔记 | Xiao Leung&#39;s Blog</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    
    
      <link rel="icon" href="/favicon.png">
    

    <link rel="stylesheet" href="/css/style.css">

    <link rel="stylesheet" href="/js/google-code-prettify/tomorrow-night-eighties.min.css">

  </head>

  <body>
<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script></body></html>
<header>

	<a id="logo" href="/" title="Xiao Leung&#39;s Blog">
	<img src="/favicon.png" alt="Xiao Leung&#39;s Blog"></a>
	
	
		<!--搜索栏-->
		<i class="js-toggle-search iconfont icon-search"></i>


<form class="js-search search-form search-form--modal" method="get" action="http://gushi.li" role="search">
	<div class="search-form__inner">
		<div>
			<i class="iconfont icon-search"></i>
			<input class="text-input" placeholder="Enter Key..." type="search">
		</div>
	</div>
</form>
	

	
		<!--侧边导航栏-->
		<a id="nav-toggle" href="#"><span></span></a>

<nav>
	<div class="menu-top-container">
		<ul id="menu-top" class="menu">
			
				
				<li class="current-menu-item">
					<a href="https://www.plasf.cn/2019/08/01/HelloWorld/" target="_blank">AboutMe</a>
				</li>
			
				
				<li class="current-menu-item">
					<a href="https://www.plasf.cn/HXCTF/" target="_blank">HXCTF</a>
				</li>
			
		</ul>
	</div>
</nav>
	

</header>

<div class="m-header ">
	<section id="hero1" class="hero">
		<div class="inner">
		</div>
	</section>
	
		<figure class="top-image" data-enable=true></figure>
	
</div>

<!--文章列表-->
<div class="wrapper">
  
    <!--文章-->
<article>
	
  
    <h1 class="post-title" itemprop="name">
      BASE64编码原理学习笔记
    </h1>
  

	<div class='post-body mb'>
		<h1 id="Base64编码原理解析"><a href="#Base64编码原理解析" class="headerlink" title="Base64编码原理解析"></a>Base64编码原理解析</h1><p>Base64编码是基于64个字符A-Z,a-z，0-9，+，/的编码方式，因为2的6次方正好为64，所以就用6bit就可以表示出64个字符</p>
<h2 id="举个栗子"><a href="#举个栗子" class="headerlink" title="举个栗子"></a>举个栗子</h2><p>‘A’ 转变为Base64编码：</p>
<p><img src="https://www.mycute.cn/static/umeditor/php/upload/20190906/15677508068341.png" alt="img"></p>
<h2 id="表格流程"><a href="#表格流程" class="headerlink" title="表格流程"></a>表格流程</h2><table>
<thead>
<tr>
<th>字符</th>
<th>A</th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody><tr>
<td>AIISC码</td>
<td>65</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>二进制</td>
<td>01000001</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>分组</td>
<td>010000</td>
<td>01000000</td>
<td>=</td>
<td>=</td>
</tr>
<tr>
<td>十进制</td>
<td>16</td>
<td>16</td>
<td>=</td>
<td>=</td>
</tr>
<tr>
<td>BASE64</td>
<td>Q</td>
<td>Q</td>
<td>=</td>
<td>=</td>
</tr>
</tbody></table>
<h2 id="BASE64查询表"><a href="#BASE64查询表" class="headerlink" title="BASE64查询表"></a>BASE64查询表</h2><pre><code class="python">[&#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;,&#39;E&#39;,&#39;F&#39;,&#39;G&#39;,&#39;H&#39;,&#39;I&#39;,&#39;J&#39;,&#39;K&#39;,&#39;L&#39;,&#39;M&#39;,&#39;N&#39;,&#39;O&#39;,&#39;P&#39;,&#39;Q&#39;,&#39;R&#39;,&#39;S&#39;,&#39;T&#39;,&#39;U&#39;,&#39;V&#39;,&#39;W&#39;,&#39;X&#39;,&#39;Y&#39;,&#39;Z&#39;,
                &#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;,&#39;e&#39;,&#39;f&#39;,&#39;g&#39;,&#39;h&#39;,&#39;i&#39;,&#39;j&#39;,&#39;k&#39;,&#39;l&#39;,&#39;m&#39;,&#39;n&#39;,&#39;o&#39;,&#39;p&#39;,&#39;q&#39;,&#39;r&#39;,&#39;s&#39;,&#39;t&#39;,&#39;u&#39;,&#39;v&#39;,&#39;w&#39;,&#39;x&#39;,&#39;y&#39;,&#39;z&#39;,
                &#39;0&#39;, &#39;1&#39;, &#39;2&#39;, &#39;3&#39;,&#39;4&#39;,&#39;5&#39;,&#39;6&#39;,&#39;7&#39;,&#39;8&#39;,&#39;9&#39;,
                &#39;+&#39;, &#39;/&#39;, &#39;=&#39;]</code></pre>
<p>从上方流程可以简单知道BASE64是先转换为AIISC码再转换为二进制进而将8位bit分组为6位bit最后不足补0，如组数不足4组，那么就用等于号（“=”）补充。最后将分组的各组再转换为10进制，按照换回来的数字当做base64编码表的形式进行查表得出结果。例如16就是在上述表中找第17位也就是数组的第16位。</p>
<h2 id="Python实现BASE64编码"><a href="#Python实现BASE64编码" class="headerlink" title="Python实现BASE64编码"></a>Python实现BASE64编码</h2><pre><code class="python">import re
base64_table = [&#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;,&#39;E&#39;,&#39;F&#39;,&#39;G&#39;,&#39;H&#39;,&#39;I&#39;,&#39;J&#39;,&#39;K&#39;,&#39;L&#39;,&#39;M&#39;,&#39;N&#39;,&#39;O&#39;,&#39;P&#39;,&#39;Q&#39;,&#39;R&#39;,&#39;S&#39;,&#39;T&#39;,&#39;U&#39;,&#39;V&#39;,&#39;W&#39;,&#39;X&#39;,&#39;Y&#39;,&#39;Z&#39;,
                &#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;,&#39;e&#39;,&#39;f&#39;,&#39;g&#39;,&#39;h&#39;,&#39;i&#39;,&#39;j&#39;,&#39;k&#39;,&#39;l&#39;,&#39;m&#39;,&#39;n&#39;,&#39;o&#39;,&#39;p&#39;,&#39;q&#39;,&#39;r&#39;,&#39;s&#39;,&#39;t&#39;,&#39;u&#39;,&#39;v&#39;,&#39;w&#39;,&#39;x&#39;,&#39;y&#39;,&#39;z&#39;,
                &#39;0&#39;, &#39;1&#39;, &#39;2&#39;, &#39;3&#39;,&#39;4&#39;,&#39;5&#39;,&#39;6&#39;,&#39;7&#39;,&#39;8&#39;,&#39;9&#39;,
                &#39;+&#39;, &#39;/&#39;, &#39;=&#39;]
def num_10_to_2(numbers):
    result=[]
    tmp=[]
    return_str=&#39;&#39;
    for number in numbers:
        while number/2!=0:
            result.append(int(number%2))
            number=int(number/2)    
        if(len(result)&lt;8):
            for i in range(0,8-len(result)):
                result.append(0)
        number_2=&#39;&#39;
        for i in range(0,len(result)):    
            nums=len(result)-i-1
            number_2=str(result[nums])+number_2
        tmp.append(number_2)
        result=[]
    for i in range(len(tmp)):
        return_str=return_str+tmp[i][::-1]
    return return_str
def num_2_to_10(number):
    number=str(number)
    nums=0
    for i  in number:
        nums=nums*2+int(i)
    return nums            

def str_to_aiisc(str_char):
    tmp=[]
    for i in str_char:
         tmp.append(int(ord(i)))    
    return tmp
def cut_string(strings,lenth):
    result =  re.findall(&#39;.{&#39;+str(lenth)+&#39;}&#39;,strings)
    result.append(strings[(len(result)*lenth):]) #把最后几位加上
    for i in range(0,6-len(result[len(result)-1])):
        result[len(result)-1]=result[len(result)-1]+str(&#39;0&#39;)
    return result
def main(strings):
    group_base = cut_string(num_10_to_2(str_to_aiisc(strings)),6)
    if(group_base[len(group_base)-1])==&#39;000000&#39;:
        group_base.pop(len(group_base)-1)
    #print(group_base)
    for i in group_base:
        print(base64_table[num_2_to_10(i)], end=&#39;&#39;)
    #print(4-int((len(group_base)/4)/0.25)%4)    
    for i in range(4-int((len(group_base)/4)/0.25)%4):
        print(&quot;=&quot;, end=&#39;&#39;)
    print(&#39;\n&#39;)    
if __name__==&#39;__main__&#39;:
    main(&#39;A&#39;)</code></pre>
<h2 id="PHP实现BASE64编码"><a href="#PHP实现BASE64编码" class="headerlink" title="PHP实现BASE64编码"></a>PHP实现BASE64编码</h2><pre><code class="php">&lt;?php
function num_10_to_2($number){
    $result=[];
    $tmp=[];
    $number_2=&#39;&#39;;
    for($i=0;$i&lt;count($number);$i++){
        while ($number[$i]/2!=0) {
        array_push($result,intval($number[$i]%2));
        $number[$i]=intval($number[$i]/2);
        }
        for($j=0;$j&lt;count($result);$j++){
            $nums = count($result)-$j-1;
            $number_2 = strval($result[$nums]).$number_2;
        }
        ///echo $number_2.&#39;&lt;br&gt;&#39;;
        array_push($tmp,$number_2);
        $number_2=&#39;&#39;;
        $result=[];
    }
    //var_dump($tmp);
    for($j=0;$j&lt;count($tmp);$j++){
    if(strlen($tmp[$j])&lt;8){
        for($i=0;$i&lt;8-strlen($tmp[$j]);$i++){
            $tmp[$j]=$tmp[$j].&#39;0&#39;;
        }
        $tmp[$j]=strrev($tmp[$j]);
        //echo $tmp[$j].&#39;&lt;br&gt;&#39;;
    }
    }

```
return implode($tmp);
```

}
function num_2_to_10($number){
    $number = strval($number);
    $nums = 0;
    for($i=0;$i&lt;strlen($number);$i++){
        $nums = $nums*2+intval(substr($number,$i,1));
    }
    return $nums;
}
function str_to_aiisc($str_char){
    $result=[];
    $str_char = strval($str_char);
    for($i=0;$i&lt;strlen($str_char);$i++){
        array_push($result,intval(ord(substr($str_char,$i,1))));
    }
    return $result;
}
function cut_string($number,$lenth){
    $number = strval($number);
    $number =  str_split($number,intval($lenth));
    for($i=0;$i&lt;count($number);$i++){
        if(strlen($number[$i])&lt;6){
            $number[$i]=$number[$i].str_repeat(&#39;0&#39;, 6-strlen($number[$i]));
        }
    }
    return $number;
}
function base64Encode($strings){
    $base64_table = [&#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;,&#39;E&#39;,&#39;F&#39;,&#39;G&#39;,&#39;H&#39;,&#39;I&#39;,&#39;J&#39;,&#39;K&#39;,&#39;L&#39;,&#39;M&#39;,&#39;N&#39;,&#39;O&#39;,&#39;P&#39;,&#39;Q&#39;,&#39;R&#39;,&#39;S&#39;,&#39;T&#39;,&#39;U&#39;,&#39;V&#39;,&#39;W&#39;,&#39;X&#39;,&#39;Y&#39;,&#39;Z&#39;,
                &#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;,&#39;e&#39;,&#39;f&#39;,&#39;g&#39;,&#39;h&#39;,&#39;i&#39;,&#39;j&#39;,&#39;k&#39;,&#39;l&#39;,&#39;m&#39;,&#39;n&#39;,&#39;o&#39;,&#39;p&#39;,&#39;q&#39;,&#39;r&#39;,&#39;s&#39;,&#39;t&#39;,&#39;u&#39;,&#39;v&#39;,&#39;w&#39;,&#39;x&#39;,&#39;y&#39;,&#39;z&#39;,
                &#39;0&#39;, &#39;1&#39;, &#39;2&#39;, &#39;3&#39;,&#39;4&#39;,&#39;5&#39;,&#39;6&#39;,&#39;7&#39;,&#39;8&#39;,&#39;9&#39;,
                &#39;+&#39;, &#39;/&#39;, &#39;=&#39;];
    $result=&#39;&#39;;
    $group_bas64 = cut_string(num_10_to_2(str_to_aiisc($strings)),6);
    for($i=0;$i&lt;count($group_bas64);$i++){
        $result=$result.$base64_table[num_2_to_10($group_bas64[$i])];
    }
    for($i=0;$i&lt;4-intval((count($group_bas64)/4)/0.25)%4;$i++){
        $result=$result.&quot;=&quot;;
    }
    return $result;
}
 echo base64Encode(&#39;ABaaa&#39;)
?&gt;</code></pre>

	</div>
	<div class="meta split">
		
			<span>本文总阅读量 <span id="busuanzi_value_page_pv"></span> 次</span>
		
		<time class="post-date" datetime="2019-09-08T13:51:09.000Z" itemprop="datePublished">2019-09-08</time>
	</div>
</article>

<!--评论-->

	
<div class="ds-thread" data-thread-key="2019-9-6-BASE64编码原理学习" data-title="BASE64编码原理学习笔记" data-url="http://www.plasf.cn/2019/09/08/2019-9-6-BASE64编码原理学习/"></div>
<script type="text/javascript">

var duoshuoQuery = {short_name:"yumemor"};
	(function() {
		var ds = document.createElement('script');
		ds.type = 'text/javascript';ds.async = true;
		ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
		ds.charset = 'UTF-8';
		(document.getElementsByTagName('head')[0]
		 || document.getElementsByTagName('body')[0]).appendChild(ds);
	})();
</script>


  
</div>


  <svg id="bigTriangleColor" width="100%" height="40" viewBox="0 0 100 102" preserveAspectRatio="none">
    <path d="M0 0 L50 100 L100 0 Z"></path>
  </svg>

  


  <div class="wrapper"></div>





<div class="fat-footer">
	<div class="wrapper">
		<div class="layout layout--center">
			<div class="layout__item palm-mb">
				<div class="media">
					<img class="headimg" src='/assets/blogImg/litten.png' alt='XiaoLeung'>
					<div class="media__body">
						<h4>兵至如归-Xiaoleung&#39;s Blog</h4>
						<p class='site-description'>Don&#39;t forget why we started</p>
					</div>
				</div>
				<div class="author-contact">
					<ul>
						
							
							<li>
				        		<a href="https://github.com/sharpleung" target="_blank">
				        			
				        				<i class="iconfont icon-github"></i>
				        			
				        		</a>
				        	</li>
						
					</ul>
				</div>
			</div>
		</div>
	</div>
</div>

<footer class="footer" role="contentinfo">
	<div class="wrapper wrapper--wide split split--responsive">
<a href="http://beian.miit.gov.cn/">粤ICP备18132442号-1</a><br>
<a target="_blank" href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=44011202000643" style="display:inline-block;text-decoration:none;height:20px;line-height:20px;"><img src="http://beian.gov.cn/img/ghs.png" style="float:left;"/><p style="float:left;height:20px;line-height:20px;margin: 0px 0px 0px 5px; color:#939393;">粤公网安备 44011202000643号</p></a><br>

		
			<span>本站总访问量 <span id="busuanzi_value_site_pv"></span> 次, 访客数 <span id="busuanzi_value_site_uv"></span> 人次</span>
		
		<span>Theme by <a href="http://github.com/justpsvm">justpsvm</a>. Powered by <a href="http://hexo.io">Hexo</a></span>
	</div>
</footer>

	<!-－这里导入了 lib.js 里面涵盖了 jQuery 等框架 所以注释掉-->
	<!--<script src="http://lib.sinaapp.com/js/jquery/2.0/jquery.min.js"></script>-->
	<script src="/js/lib.js"></script>
	<script src="/js/google-code-prettify/prettify.js"></script>
	<script src="/js/module.js"></script>
	<script src="/js/script.js"></script>
	
		<script async src="http://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>
	
	<script type='text/javascript'>
		//代码高亮
		$(document).ready(function(){
	 		$('pre').addClass('prettyprint linenums').attr('style', 'overflow:auto;');
   			prettyPrint();
		});
	</script>
	<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script><script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"log":false,"pluginJsPath":"lib/","pluginModelPath":"assets/","pluginRootPath":"live2dw/","tagMode":false});</script></body>
</html>

<script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
 <script type="text/javascript"> /* 鼠标点击特效 - 7Core.CN */ var a_idx = 0;jQuery(document).ready(function($) {$("body").click(function(e) {var a = new Array("富强", "民主", "文明", "和谐", "自由", "平等", "公正" ,"法治", "爱国", "敬业", "诚信", "友善");var $i = $("<span/>").text(a[a_idx]); a_idx = (a_idx + 1) % a.length;var x = e.pageX,y = e.pageY;$i.css({"z-index": 100000000,"top": y - 20,"left": x,"position": "absolute","font-weight": "bold","color": "#ff6651"});$("body").append($i);$i.animate({"top": y - 180,"opacity": 0},1500,function() {$i.remove();});});}); </script>

